import { createRouter, createWebHistory, type RouteLocationNormalized } from "vue-router";
import { ErrorType } from "@/service/configTypes";
import { useAuthStore } from "@/store/auth";
import { message } from "ant-design-vue";

const router = createRouter({
  // 这里的import.meta.env.BASE_URL取值于vite.config.js中的base属性。
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/home",
      name: "home",
      component: () => import("@/App.vue"),
      meta: {
        requiresAuth: true,
        requiredRoles: ["admin"],
      },
    },
    {
      path: "/test",
      name: "test",
      component: () => import("@/views/test.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/chat",
      name: "chat",
      component: () => import("@/views/chat.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/ws-chat",
      name: "wsChat",
      component: () => import("@/views/ws-chat.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/typeit",
      name: "typeIt",
      component: () => import("@/views/typeit/index.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/typeit/dialog",
      name: "dialogue",
      component: () => import("@/views/typeit/dialogue.vue"),
      meta: { requiresAuth: false },
    },
  ],
});

router.beforeEach(async (to: RouteLocationNormalized) => {
  const authStore = useAuthStore();

  // 公开路由直接放行
  if (to.meta.public) return true;

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    // 验证token是否存在
    if (!authStore.isAuthenticated) {
      return redirectToLogin(to);
    }
  }

  // 检查用户角色权限
  if (to.meta.requiredRoles) {
    const requiredRoles = to.meta.requiredRoles as string[];
    if (!authStore.hasRoles(requiredRoles)) {
      // 重定向到无权限页面
      return { name: "Forbidden" };
    }
  }
});

// 重定向到登录页
function redirectToLogin(to: RouteLocationNormalized) {
  // 避免在登录页循环重定向
  if (to.name === "Login") return true;

  return {
    path: "/login",
    query: { redirect: to.fullPath },
  };
}

// 全局错误处理
router.onError(error => {
  if (error.type === ErrorType.AUTH_ERROR) {
    message.error("认证失败，请重新登录");
  } else if (error.type === ErrorType.PERMISSION_ERROR) {
    message.error("您没有访问此页面的权限");
  }
});

export default router;
